const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const port = 3306;

app.use(cors());
app.use(bodyParser.json());

let posts = []; // 模拟数据库

// 获取所有文章
app.get('/api/posts', (req, res) => {
  res.json(posts);
});

// 获取单个文章
app.get('/api/posts/:id', (req, res) => {
  const post = posts.find(p => p.id === parseInt(req.params.id));
  res.json(post);
});

// 创建新文章
app.post('/api/posts', (req, res) => {
  const newPost = { id: posts.length + 1, ...req.body };
  posts.push(newPost);
  res.status(201).json(newPost);
});

// 更新文章
app.put('/api/posts/:id', (req, res) => {
  const index = posts.findIndex(p => p.id === parseInt(req.params.id));
  if (index !== -1) {
    posts[index] = { id: parseInt(req.params.id), ...req.body };
    res.json(posts[index]);
  } else {
    res.status(404).send('文章未找到');
  }
});

// 删除文章
app.delete('/api/posts/:id', (req, res) => {
  posts = posts.filter(p => p.id !== parseInt(req.params.id));
  res.status(204).send(); // 返回204 No Content
});

// 启动服务器
app.listen(port, () => {
  console.log(`API server is running at http://localhost:${port}`);
}); 

